package utils;



import model.VersionBean;

import java.io.File;

/**
 * Created by lincl on 2018/12/10.
 */
public class UpdateTool {
    private static String ProjectFolderPath = null;
    public static VersionBean curVersion;
    public static VersionBean newVersion;


    public static void updateVersionFile(){
        File versionFile = new File(getProjectFolderPath(), Constant.Version_File_Name);
        versionFile.delete();
        File newVersionFile = new File(getProjectFolderPath(),
                Constant.Update_Dir_Name+ "/" + Constant.Version_File_Name);
        newVersionFile.renameTo(versionFile);
    }

    public static VersionBean checkUpdate(){
        try {
            String root = UpdateTool.getProjectFolderPath();
            //获取旧版本信息
            if(curVersion==null){
                File versionFile = new File(root, Constant.Version_File_Name);
                curVersion = FileUtils.readVersionBean(versionFile);
                if(curVersion==null){
                    MonologUtils.alert("解析版本文件错误，无法更新");
                    return null;
                }
            }

            //获取新版本信息
            File newVersionFile = new File(root, Constant.Update_Dir_Name+"/"+ Constant.Version_File_Name);
            FileUtils.downLoadFile(newVersionFile);
            newVersion = FileUtils.readVersionBean(newVersionFile);

            if(curVersion.getCurVersion().equals(newVersion.getCurVersion())){
                MonologUtils.alert("您的版本已经是最新的");
                return null;
            }
            return newVersion;
        }catch (Exception e){
            MonologUtils.alert("确定版本信息错误");
            e.printStackTrace();
            return null;
        }
    }

    public static String getProjectFolderPath(){
        if(ProjectFolderPath!=null){
            return ProjectFolderPath;
        }
        String root = UpdateTool.class.getResource("").getPath();
        if(root.startsWith("file:/")){
            root = root.substring(6);
        } else if(root.startsWith("/")){
            root = root.substring(1);
        }

        int i;
        if( (i = root.indexOf(Global.Exe_Name + "svnPacking.jar!"))!=-1){
            //存在 生成环境 jar包
            root = root.substring(0, i);
        } else {
            root = root.substring(0, root.lastIndexOf(Global.Exe_Name));
        }
        root = new File(root).getParent();
        //创建更新文件夹
        File updateDir = new File(root, Constant.Update_Dir_Name);
        if(!updateDir.exists()){
            updateDir.mkdirs();
        }

        return root;
    }
}
